<template>
  <div class="add-wrap" v-loading="loading">
    <Breadcrumb
      :titles="titles"
      :showBack="showBack"
    ></Breadcrumb>
    <div class="body">
      <div class="project">
        <el-form
          :model="basicForm"
          label-position="top"
          :rules="basicRules"
          ref="basicFormRef"
        >
          <!-- 基本信息 -->
          <div class="project-part">
            <div
              class="project-part-title project-part-title1"
            >
              基本信息
            </div>
            <div class="project-part-content">
              <el-row :gutter="24">
                <!-- <el-col
                  :xs="24"
                  :sm="24"
                  :md="12"
                  :lg="8"
                  :xl="6"
                >
                  <el-form-item
                    label="图号"
                    prop="figureNumber"
                  >
                    <el-input
                      v-model="basicForm.figureNumber"
                      :disabled="isDetail"
                    ></el-input>
                  </el-form-item>
                </el-col> -->
                <el-col
                  :xs="24"
                  :sm="24"
                  :md="12"
                  :lg="8"
                  :xl="6"
                >
                  <el-form-item
                    label="项目名称"
                    prop="projectName"
                  >
                    <el-input
                      v-model="basicForm.projectName"
                      :disabled="isDetail"
                    ></el-input>
                  </el-form-item>
                </el-col>
                <el-col
                  :xs="24"
                  :sm="24"
                  :md="12"
                  :lg="8"
                  :xl="6"
                >
                  <el-form-item
                    label="街道"
                    prop="streetId"
                  >
                    <el-select
                      placeholder=""
                      v-model="basicForm.streetId"
                      clearable
                      :disabled="isDetail"
                      filterable
                      multiple
                    >
                      <el-option
                        v-for="item in streetOptions"
                        :key="item.pkid"
                        :label="item.areaName"
                        :value="item.pkid"
                      >
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <!-- <el-col
                  :xs="24"
                  :sm="24"
                  :md="12"
                  :lg="8"
                  :xl="6"
                >
                  <el-form-item
                    label="管护年度"
                    prop="manageYear"
                  >
                    <el-date-picker
                      v-model="basicForm.manageYear"
                      type="year"
                      :disabled="isDetail"
                      value-format="yyyy"
                    >
                    </el-date-picker>
                  </el-form-item>
                </el-col> -->
                <!-- <el-col
                  :xs="24"
                  :sm="24"
                  :md="12"
                  :lg="8"
                  :xl="6"
                >
                  <el-form-item
                    label="管护费用"
                    prop="manageCost"
                  >
                    <el-input
                      v-model="basicForm.manageCost"
                      :disabled="isDetail"
                      ><template slot="append"
                        >万元</template
                      >
                    </el-input>
                  </el-form-item>
                </el-col> -->
                <el-col
                  :xs="24"
                  :sm="24"
                  :md="12"
                  :lg="8"
                  :xl="6"
                >
                  <el-form-item
                    label="拆迁面积"
                    prop="area"
                  >
                    <el-input
                      v-model="basicForm.area"
                      :disabled="isDetail"
                      ><template slot="append"
                        >平方米</template
                      >
                    </el-input>
                  </el-form-item>
                </el-col>
              </el-row>
            </div>
          </div>
          <div class="project-part">
            <div
              class="project-part-title project-part-title1"
            >
              拆迁范围
            </div>
            <div class="project-part-content">
              <el-row :gutter="24">
                <el-col :span="24">
                  <el-form-item
                    label="拆迁范围文件（shp格式）"
                  >
                    <el-upload
                      action="#"
                      class="shp-upload"
                      :show-file-list="false"
                      :drag="false"
                      :on-change="onFileSelect"
                      :auto-upload="false"
                      v-if="!isDetail"
                      accept=".zip"
                    >
                      <span>
                        <span
                          class="shp-upload-icon"
                        ></span>
                        <span class="shp-upload-text"
                          >点击上传</span
                        >
                      </span>
                    </el-upload>
                    <el-input
                      v-model="basicForm.fileName"
                      placeholder="暂无文件"
                      :disabled="isDetail"
                      clearable
                    ></el-input>
                    <el-progress
                      v-if="
                        progressNum !== 0 &&
                        progressNum !== 100
                      "
                      :percentage="progressNum"
                      color="#409eff"
                    ></el-progress>
                    <el-button
                      size="small"
                      class="preview-button"
                      @click="previewMap"
                      >地图预览</el-button
                    >
                  </el-form-item>
                </el-col>
              </el-row>
            </div>
          </div>
          <!-- 节点信息 -->
          <div class="project-part">
            <div
              class="project-part-title project-part-title1"
            >
              附件材料
            </div>
            <div class="project-part-content">
              <table class="table">
                <thead>
                  <tr>
                    <th>序号</th>
                    <th>材料名称</th>
                    <th style="width: 40%">上传文件</th>
                    <th style="width: 20%" v-if="!isDetail">
                      操作
                    </th>
                  </tr>
                </thead>
                <tbody>
                  <tr
                    v-for="(
                      item, index
                    ) in basicForm.landDataManageAttachmentRelList"
                    :key="index"
                  >
                    <td>{{ item.orderIndex }}</td>
                    <td>{{ item.attachmentName }}</td>
                    <td>
                      <UploadVue
                        v-model="item.attachmentList"
                        :disabled="isDetail"
                      />
                    </td>
                    <td v-if="!isDetail">
                      <div class="table-btn"></div>
                    </td>
                  </tr>
                </tbody>
              </table>
            </div>
          </div>
        </el-form>
      </div>
    </div>
    <div class="line" v-show="!isDetail">
      <el-button @click="saveInfo" class="save-btn"
        >保存</el-button
      >
    </div>
    <customizeDialog
      :visible="dialogMapVisible"
      @update:visible="dialogMapVisible = $event"
      ref="dialog"
      :title="`${headerTitle}`"
      :titleTip="`当前面积：${currentArea}m²`"
      :width="'1200px'"
      top="100px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :has-footer="false"
      customPadding="0px"
    >
      <div
        v-loading="mapLoading"
        element-loading-text="文件正在解析中，请稍后..."
      >
        <MapView
          :viewer-id="viewerId"
          :key="countMapLoad"
          @onload="onMapLoad"
        />
        <Utool
          :viewerId="viewerId"
          :position="{ top: '60px', right: '20px' }"
          :t="[]"
          :b="[
            {
              title: '初始位置',
              icon: 'dingwei'
            }
          ]"
          :showMore="false"
        ></Utool>
      </div>
    </customizeDialog>
  </div>
</template>

<script>
import request from '@/utils/request'
import Breadcrumb from '@/components/breadcrumb'
import UploadVue from '@/components/upload'
import {
  addProjectInfo,
  queryProjectDetail,
  queryStreetList
} from '@/api/landInfo'
import { dwgFileById } from '@/api/projectMessage'
import MapView from '@/components/mapView'
import Utool from '@/components/utool/index-land'
import customizeDialog from '@/components/checkHistory/customizeDialog.vue'
import * as turf from '@turf/turf'

let _layerManager, _viewer
const mapViewer = {}

export default {
  props: {
    pkid: String,
    title: String,
    isEdit: {
      type: Boolean,
      default: false
    },
    isDetail: {
      type: Boolean,
      default: false
    },
    showBack: {
      type: Boolean,
      default: true
    }
  },
  components: {
    Breadcrumb,
    UploadVue,
    MapView,
    Utool,
    customizeDialog
  },
  data() {
    return {
      basicForm: {
        // figureNumber: '',
        projectName: '',
        streetId: [],
        // manageYear: '',
        // manageCost: '',
        fileList: [],
        fileName: '',
        shpFile: '',
        shpJson: '',
        area: '',
        landDataManageAttachmentRelList: [
          {
            orderIndex: 1,
            attachmentName: '附件材料',
            attachmentList: []
          }
          // {
          //   orderIndex: 2,
          //   attachmentName: '发展服务局上会材料',
          //   attachmentList: []
          // }
        ]
      },
      basicRules: {
        projectName: [
          {
            required: true,
            message: '请输入事项名称',
            trigger: 'blur'
          }
        ],
        area: [
          {
            pattern: /^(([1-9]{1}\d*)|(0{1}))(\.\d{1,2})?$/,
            message: '请输入最多两位小数的正数',
            trigger: 'blur'
          }
        ]
      },
      loading: false,
      streetOptions: [],

      dialogMapVisible: false,
      viewerId: 'dwgMap',
      countMapLoad: 0,
      uploadLoading: false,
      progressNum: 0,
      currentFeature: '',
      currentArea: 0,
      headerTitle: '',
      mapLoading: false
    }
  },
  computed: {
    titles() {
      return [this.title]
    }
  },
  watch: {
    'basicForm.fileName': function (val) {
      if (val === '') {
        this.basicForm.shpFile = ''
        this.basicForm.shpJson = ''
      }
    }
  },
  mounted() {
    this.getStreetData()
    if (this.isEdit) {
      this.getDetailInfo()
    }
  },
  methods: {
    // 获取街道
    async getStreetData() {
      let res = await queryStreetList({ level: 3 })
      this.streetOptions = res.data
    },
    // 获取项目详情
    getDetailInfo() {
      this.loading = true
      queryProjectDetail(this.pkid).then((res) => {
        if (res.success) {
          const data = {
            ...res.data.landDataManage,
            streetId: res.data.landDataManage.streetId
              ? res.data.landDataManage.streetId.split(',')
              : [],
            landDataManageAttachmentRelList:
              res.data.landDataManageAttachmentRelList
          }
          this.basicForm = data
        }
        this.loading = false
      })
    },

    // 保存信息
    saveInfo() {
      this.$refs.basicFormRef.validate((res) => {
        if (res) {
          const data = JSON.parse(
            JSON.stringify(this.basicForm)
          )
          data.landDataManageAttachmentRelList.forEach(
            (item) => {
              if (
                item.attachmentList &&
                item.attachmentList.length > 0
              ) {
                const files = []
                item.attachmentList.forEach((element) => {
                  files.push({
                    attachmentId: element.response.data,
                    pkid: element.pkid,
                    refId: element.refId
                  })
                })
                item.attachmentList = files
              }
            }
          )
          const formData = {
            landDataManage: {
              pkid: this.basicForm.pkid,
              // figureNumber: this.basicForm.figureNumber,
              projectName: this.basicForm.projectName,
              streetId: this.basicForm.streetId.join(','),
              // manageYear: this.basicForm.manageYear,
              // manageCost: this.basicForm.manageCost,
              area: this.basicForm.area,
              shpFile: this.basicForm.shpFile,
              shpJson: this.basicForm.shpJson
            },
            landDataManageAttachmentRelList:
              data.landDataManageAttachmentRelList
          }
          console.log('this.basicForm', this.basicForm)

          addProjectInfo(formData).then((res) => {
            if (res.success) {
              this.$message.success('保存成功')
              this.$router.push({
                path: '/wisdomLand/ManagementDataManagement/list',
                query: { refresh: Date.now() }
              })
            }
          })
        }
      })
    },

    // 上传文件
    onFileSelect(file) {
      console.log('file', file)
      this.uploadLoading = true
      const data = new FormData()
      data.append('file', file.raw)
      request({
        method: 'post',
        url: '/map/map/upload/getGeoJson',
        data: data,
        onUploadProgress: (progressEvent) => {
          this.progressNum = parseInt(
            ((progressEvent.loaded / progressEvent.total) *
              100) |
              0,
            10
          )
        }
      })
        .then((res) => {
          if (res.success) {
            const id = res.data.fileId
            const geojson = res.data.geoJson
            console.log('geojson-----', geojson)
            this.$set(this.basicForm, 'fileName', file.name)
            this.$set(this.basicForm, 'shpFile', id)
            this.$set(this.basicForm, 'shpJson', geojson)
            this.$message.success('上传成功')
          } else {
            this.$message.error(res.message)
          }

          this.uploadLoading = false
        })
        .catch(() => {
          this.uploadLoading = false
        })
    },

    // 地图加载
    onMapLoad({ id, viewer }) {
      _viewer = viewer

      _viewer.scene.imageryLayers.addImageryProvider(
        new Cesium.TiandituImageryProvider({
          mapStyle: null,
          token: 'a49a9220798216424e34b531cb3fa5b2',
          url: 'https://t0.tianditu.gov.cn/img_w/wmts'
        }),
        0
      )
      const geojson = _viewer.dataSources.add(
        Cesium.GeoJsonDataSource.load(this.currentFeature)
      )
      _viewer.flyTo(geojson)
    },

    // 地图预览
    previewMap() {
      if (this.basicForm.shpFile) {
        this.previewMapById(
          this.basicForm.shpFile,
          this.basicForm.shpJson
        )
        this.dialogMapVisible = true
      } else {
        this.$message.warning('请先上传文件再预览')
      }
    },

    // 通过文件id预览
    previewMapById(id, geojsonStr) {
      this.headerTitle = '地图预览'
      this.mapLoading = true

      if (!geojsonStr) {
        dwgFileById(id)
          .then((res) => {
            if (res.success) {
              this.currentFeature = JSON.parse(res.data)
              const area = turf.area(this.currentFeature)
              this.currentArea = area ? area.toFixed(2) : 0
              // 更新地图预览
              this.countMapLoad++
            }
            this.mapLoading = false
          })
          .catch(() => {
            this.mapLoading = false
          })
      } else {
        this.currentFeature = JSON.parse(geojsonStr)
        const area = turf.area(this.currentFeature)
        this.currentArea = area ? area.toFixed(2) : 0
        // 更新地图预览
        this.countMapLoad++
        this.mapLoading = false
      }
    }
  }
}
</script>

<style lang="scss" scoped>
@import '~@/assets/css/form.scss';
.add-wrap {
  .table {
    border-collapse: collapse;
    width: 100%;
    box-sizing: border-box;
    thead {
      background-color: #f2f6fb;
    }
    td,
    th {
      font-size: 14px;
      font-family: PingFang SC;
      font-weight: bold;
      color: #6b767d;
      line-height: 42px;
      border: 1px solid #f2f6fb;
      text-align: center;
    }
    td {
      font-weight: normal;
    }
    tbody {
      tr {
        td {
          &:nth-child(1) {
            width: 50px;
          }
          &:nth-child(2) {
            width: 300px;
          }
          &:nth-child(3) {
            width: 300px;
          }
          &:nth-child(4) {
            max-width: 1000px;
          }
          &:nth-child(5) {
            width: 300px;
          }
        }
      }
    }
  }
  ::v-deep .el-upload {
    position: absolute !important;
    right: -25% !important;
    top: 50% !important;
    transform: translate(50%, -50%) !important;
  }

  .shp-upload {
    cursor: pointer;
    height: 0px;
    ::v-deep .el-upload {
      position: relative !important;
      right: 0 !important;
      top: 0 !important;
      transform: none !important;
    }

    &-text {
      position: absolute;
      top: -49px;
      left: 260px;
      color: #00baff;
      min-width: 60px;
      line-height: 14px;
    }

    &-icon {
      position: absolute;
      width: 16px;
      height: 14px;
      top: -49px;
      left: 240px;
      background: url('~@/assets/images/wisdom-construction/upload-file.png');
      background-size: 100% 100%;
    }
  }
  .preview-button {
    position: absolute;
    top: 5px;
    left: 330px;
    background: #497fa3;
    border: 1px solid #497fa3;
    border-radius: 2px;
    color: white;
  }

  ::v-deep .cesium-viewer {
    height: 520px !important;
  }
}
</style>
